<?php

/**
 *   OPENSHOP     Supply Chain Management,SCM
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: scm.php,v 1.0 2009/07/13 09:36:58 created $
 *   @author      FillBag <fillbag@hotmail.com>
 */


define('IN_OS', true);
require(dirname(__FILE__) . '/includes/init.php');
require(dirname(__FILE__) . '/includes/lib_scm.php');

$action 			= 	isset($_REQUEST['act']) ? $_REQUEST['act'] : 'list_purchase_order';
$exc_purchase		= 	new exchange($os->table('scm_purchase_order'), $db, 'order_id', 'order_sn');
$exc_type 			= 	new exchange($os->table('scm_purchase_goods'), $db, 'rec_id', 'goods_brief');
$exc_enter 		    = 	new exchange($os->table('scm_enter_order'), $db, 'order_id', 'order_sn');
$exc_return 		= 	new exchange($os->table('scm_return_order'), $db, 'order_id', 'order_sn');
$exc_pay 			= 	new exchange($os->table('scm_payment'), $db, 'pay_id', 'pay_name');


/*------------------------------------------------------ */
//-- 采购单列表
/*------------------------------------------------------ */
if($_REQUEST['act']=='list_purchase_order'){	
    /* 检查权限 */
    admin_priv();   
    
    $smarty->assign('ur_here',      '采购单列表');    
	$smarty->assign('action_link',  array('text' => '添加采购单', 'href' => 'scm.php?act=add_purchase_order'));    
    $smarty->assign('full_page',    1);
    
    $list = scm_purchase_order_list();  
    $smarty->assign('status_list', 	        scm_order_status('purchase'));   
    $smarty->assign('order_list', 	        $list['item']);    
    $smarty->assign('filter',        		$list['filter']);
    $smarty->assign('page_count',    		$list['page_count']); 
    $smarty->assign('record_count',  		$list['record_count']);
    
    assign_query_info();
    $smarty->display('scm_purchase_order_list.tpl');	
}
/*------------------------------------------------------ */
//-- 采购单翻页，排序
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='query_purchase_order'){
	
    $list = scm_purchase_order_list();
    $smarty->assign('order_list',           $list['item']);
    $smarty->assign('filter',         		$list['filter']);
    $smarty->assign('record_count',   		$list['record_count']);
    $smarty->assign('page_count',     		$list['page_count']);
    
    make_json_result($smarty->fetch('scm_purchase_order_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  
}
/*------------------------------------------------------ */
//-- 添加、编辑采购单
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add_purchase_order' || $_REQUEST['act'] == 'edit_purchase_order')
{
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'add_purchase_order';
    /* 权限检查 */
    $priv_str = $is_add ? 'add_scm_purchase_order' : 'edit_scm_purchase_order';
    admin_priv($priv_str);
    
    $smarty->assign('form_action', $is_add ? 'insert_purchase_order' : 'update_purchase_order');

    /* 初始化、取得采购订单信息 */
    if ($is_add)
    {
        $order = array(
            'order_id'              	=> 0,
            'order_sn'   	        	=> create_fast_order_sn('purchase'),
            'supplier_id'   			=> 0,        
            'depot_id'   				=> 0,
            'seat_id'      	        	=> 0,
            'discount'         			=> 1,
            'formated_deliver_time'     => local_date('Y-m-d', local_strtotime('+1 months')),
            'order_brief'               => '',                              
            'formated_add_time'         => local_date('Y-m-d')
        );
    }
    else
    {
        if (empty($_GET['id']))
        {
            sys_msg('invalid param');
        }
        
        $order = scm_purchase_order_info($_GET['id']);
        
        if (empty($order) || ($order['order_status'] <> 0))
        {
            sys_msg('采购单不存在或状态无效');
        }
    }    

    $smarty->assign('order', $order);


    /* 显示模板 */
    if ($is_add)
    {
        $smarty->assign('ur_here', '添加采购单');
    }
    else
    {
        $smarty->assign('ur_here', '编辑采购单');
    }
    if ($is_add)
    {
        $href = 'scm.php?act=list_purchase_order';
    }
    else
    {
        $href = 'scm.php?act=list_purchase_order&' . list_link_postfix();
    }
    $smarty->assign('action_link', array('href' => $href, 'text' => '采购单列表'));
    
    assign_query_info();    
    $smarty->display('scm_purchase_order_edit.tpl');     
}
/*------------------------------------------------------ */
//-- 提交添加、编辑采购单
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'insert_purchase_order' || $_REQUEST['act'] == 'update_purchase_order')
{
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert_purchase_order';
    /* 权限检查 */
    $priv_str = $is_add ? 'add_scm_purchase_order' : 'edit_scm_purchase_order';
    admin_priv($priv_str);

    /* 提交值 */
    $order = array(
        'order_id'     			            => intval($_POST['id']),
        'order_sn'   			            => sub_str($_POST['order_sn'], 60, false),
		'supplier_id'   			        => intval($_POST['supplier_id']),        
		'depot_id'   			        	=> 0,
		'seat_id'      				        => 0,
		'discount'   						=> floatval($_POST['discount']),
		'deliver_time'         				=> local_strtotime($_POST['deliver_time']),
		'order_brief'    				    => trim($_POST['order_brief']),
		'add_time'         					=> local_strtotime($_POST['add_time'])
    );

    /* 判断单据编号是否重复 */
    if (!$exc_purchase->is_only('order_sn', $order['order_sn'], $order['order_id']))
    {
        sys_msg('该单据编号已存在，请您换一个编号');
    }

    /* 保存采购订单信息 */
    if ($is_add)
    {
        $db->autoExecute($os->table('scm_purchase_order'), $order, 'INSERT');
        $order['order_id'] = $db->insert_id();
    }
    else
    {
        $db->autoExecute($os->table('scm_purchase_order'), $order, 'UPDATE', "order_id = '$order[order_id]'");
    }

    /* 记日志 */
    if ($is_add)
    {
        admin_log('采购单, 单号 ' . $order['order_sn'], 'add', 'scm_purchase_order');
        $goto_act = 'edit_goods&type=purchase';
    }
    else
    {
        admin_log('采购单, 单号 ' . $order['order_sn'], 'edit', 'scm_purchase_order');
        $goto_act = 'info_purchase_order';
    }

    /* 清除缓存 */
    clear_cache_files();

 	os_header("Location: scm.php?act=$goto_act&id=$order[order_id]");
	exit;
}
/*------------------------------------------------------ */
//-- 删除采购单
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='remove_purchase_order'){

    check_authz_json('drop_scm_purchase_order');

    $order_id = intval($_GET['id']);
    $order = scm_purchase_order_info($order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	if($_REQUEST['is_ajax']==1){
    		make_json_error('采购单不存在或状态无效');
    	}else{
    		sys_msg('采购单不存在或状态无效');
    	}
    	exit;
    }
    
    if($db->query("DELETE FROM " . $os->table('scm_purchase_order') . " WHERE order_id='$order_id'")){
	    /* 记日志 */
	    admin_log(sprintf('采购单 s%', $order['order_sn']), 'remove', 'scm_purchase_order');	
	    $db->query("DELETE FROM " . $os->table('scm_purchase_goods') . " WHERE order_id='$order_id'");
    }

    /* 清除缓存 */
    clear_cache_files();
    if($_REQUEST['is_ajax']==1){
    	$url = 'scm.php?act=query_purchase_order&' . str_replace('act=remove_purchase_order', '', $_SERVER['QUERY_STRING']);
    }else{
    	$url = 'scm.php?act=list_purchase_order';
    }
    os_header("Location: $url\n");
    exit;		
}
/*------------------------------------------------------ */
//-- 查看采购单
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='info_purchase_order'){
    if (empty($_GET['id']))
    {
        sys_msg('invalid param');
    }	
    $order_id = intval($_GET['id']);
    
    $order = scm_purchase_order_info($order_id);
    
	if (empty($order))
	{
		sys_msg('采购单不存在');
	}
	
    $smarty->assign('ur_here', '查看采购单');
    $smarty->assign('action_link', array('href' => 'scm.php?act=list_purchase_order', 'text' => '采购单列表'));
	
    $sql = "SELECT MAX(order_id) FROM " . $os->table('scm_purchase_order') . " WHERE order_id < '$order[order_id]'";    
    $smarty->assign('prev_id', $db->getOne($sql));
    $sql = "SELECT MIN(order_id) FROM " . $os->table('scm_purchase_order') . " WHERE order_id > '$order[order_id]'";
    $smarty->assign('next_id', $db->getOne($sql));    
      
	$smarty->assign('order', $order);
	
	$goods_list = scm_order_goods('purchase', $order_id);
	
	$smarty->assign('goods_list', $goods_list);

	/* 取得订单操作记录 */
	$smarty->assign('action_list', scm_order_action('purchase', $order_id));
	
    assign_query_info();       	
    $smarty->display('scm_purchase_order_info.tpl');  		
}
/*------------------------------------------------------ */
//-- 操作采购单状态（载入页面）
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='operate_purchase_order'){
    if (empty($_POST['order_id']))
    {
        sys_msg('invalid param');
    }	
    $order_id   = intval($_POST['order_id']);
    $order      = scm_purchase_order_info($order_id);
	if (empty($order))
	{
		sys_msg('采购单不存在');
	}
	if($order['goods_number']<=0){
		sys_msg('采购单没有商品不能做任何操作');		
	}
    $action_note = empty($_POST['action_note']) ? '' : trim($_POST['action_note']);
    $goto_act    = "info_purchase_order&id=$order_id";
    /* 仓储审核通过 */
    if (isset($_POST['depot_audit']))
    {
        if($order['order_status']<>0 && $order['order_status']<>2){
    		sys_msg('无效状态无法仓储审核通过');
    	}
        $operation      = 'order_status';
        $order_status   = 1;
    }

    /* 仓储审核不通过 */
    if (isset($_POST['depot_unaudit']))
    {
        if($order['order_status']<>0 && $order['order_status']<>1){
    		sys_msg('无效状态无法仓储审核不通过');
    	}
        $operation      = 'order_status';
        $order_status   = 2;
    }

    /* 财务审核通过 */
    if (isset($_POST['finance_audit']))
    {
        if($order['order_status']<>1 && $order['order_status']<>4){
    		sys_msg('无效状态无法财务审核通过');
    	}
        $operation      = 'order_status';
        $order_status   = 3;
    }

    /* 财务审核不通过 */
    if (isset($_POST['finance_unaudit']))
    {
        if($order['order_status']<>1 && $order['order_status']<>3){
    		sys_msg('无效状态无法财务审核不通过');
    	}
        $operation      = 'order_status';
        $order_status   = 4;
    }
    
    /* 作废 */
    if (isset($_POST['disaffirm']))
    {
     	if($order['order_status']<>0 && $order['order_status']<>2){
    		sys_msg('无效状态无法作废');
    	}
    	
        $operation      = 'order_status';
        $order_status   = 7;
    }
    
    /* 生成采购入库单 */
    if(isset($_POST['enter'])){
	    if($order['order_status'] <> 3){
	    	sys_msg('无效状态无法生成采购入库单');	
	    }   
	    $order_sn       = create_fast_order_sn('enter');
		$enter_order_id = create_scm_enter_order($order_id, $order_sn);
		create_scm_enter_goods($enter_order_id, $order_id);
	    update_scm_order('enter', $enter_order_id, array('purchase_order_id'=>$order_id));
	                            		
        $operation      = 'order_status';
        $order_status   = 5;
		$goto_act    = "info_enter_order&id=$enter_order_id";	       	
    }
    
    /* 完成 */
    if (isset($_POST['confirm']))
    {
     	if($order['order_status']<>5){
     		sys_msg('无效状态无法完成');
    	}
        $operation      = 'order_status';
        $order_status   = 6;
    }
    update_scm_order('purchase', $order_id, array($operation => $order_status));
	update_scm_order_action('purchase', $order['order_sn'], $order_status, $action_note);
    os_header("Location: scm.php?act=$goto_act");
    exit;	    
}
/*------------------------------------------------------ */
//-- 编辑单据商品
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='edit_goods'){	
    /* 检查权限 */
//    admin_priv();  
      
    if(empty($_GET['id']) || !in_array($_GET['type'], array('purchase', 'enter', 'return')))
    {
    	sys_msg('invalid param');
    }    
    
    $order_id     = intval($_GET['id']);
    $order_type   = trim($_GET['type']);	
    $order        = get_fast_scm_order_info($order_type, $order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	sys_msg(fast_scm_order_ur($order_type).'不存在或状态无效');
    }
    
    $smarty->assign('ur_here', '编辑'.fast_scm_order_ur($order_type).'商品');
    $smarty->assign('action_link', array('href' => 'scm.php?act=list_'.$order_type.'_order', 'text' => fast_scm_order_ur($order_type).'列表'));	  
     
	$smarty->assign('order', $order);   
	
    $goods_list = scm_order_goods($order_type, $order_id);
    $smarty->assign('goods_list', $goods_list);
             
    assign_query_info();
    $smarty->display('scm_order_goods_edit.tpl');
}

elseif($_REQUEST['act']=='check_alone_discount'){
    if(empty($_GET['order_id']) || empty($_GET['goods_id']) || !in_array($_GET['type'], array('purchase', 'enter', 'return')))
    {
    	make_json_error('invalid param');
    	exit();
    } 
    $result = array('error'=>0, 'message'=>'', 'content'=>''); 
    
    $order_id     = intval($_GET['order_id']);
    $goods_id     = intval($_GET['goods_id']);
    $discount     = floatval($_GET['discount']);
    $order_type   = trim($_GET['type']);	
    $order        = get_fast_scm_order_info($order_type, $order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	make_json_error(fast_scm_order_ur($order_type).'不存在或状态无效');
    	exit();
    }
    $sql = "SELECT COUNT(*) FROM ".$os->table('scm_'.$order_type.'_goods')." WHERE order_id='$order_id' AND goods_id='$goods_id' AND discount<>'$discount'";
    $not_alone_discount = $db->getOne($sql);
    if($not_alone_discount && $not_alone_discount>0){
    	$sql = "SELECT g.goods_name,g.goods_sn,og.discount FROM ".$os->table('scm_'.$order_type.'_goods').
    	       " og LEFT JOIN ".$os->table('goods')." g ON og.goods_id=g.goods_id WHERE og.order_id='$order_id'".
    	       " AND og.goods_id='$goods_id' GROUP BY og.goods_id";
    	$info = $db->getRow($sql);
    	$result['error'] = 1;
    	$result['message'] = $info['goods_name'].'['.$info['goods_sn'].']已经存在,将覆盖折扣 '.$info['discount'];
    } 	
    make_json_result('', '', $result);
}
/*------------------------------------------------------ */
//-- 提交编辑单据商品
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='edit_post_goods'){
    if (empty($_POST['order_id']) || empty($_POST['goodslist']) || !in_array($_POST['type'], array('purchase', 'enter', 'return')))
    {
        sys_msg('invalid param');
    }	
    $order_id     = intval($_POST['order_id']);
    $order_type   = trim($_POST['type']);
    $order        = get_fast_scm_order_info($order_type, $order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	sys_msg(fast_scm_order_ur($order_type).'不存在或状态无效');
    }
    
    $supplier_id = intval($_POST['supplier_id']);
    $discount    = (!empty($_POST['discount']) && $_POST['discount']>0 && $_POST['discount']<1)  ? floatval($_POST['discount']) : 1;	
    if(!is_array($_POST['goods_nums'])){
         sys_msg('你必须设置商品数量');   	
    }  
	edit_scm_order_goods($order_type, $order_id, $supplier_id, $_POST['goods_nums'], $discount);
	
    $order_stat = scm_order_amount($order_type, $order_id);
    /* 更新商品总金额和订单总金额 */
    update_scm_order($order_type, $order_id, array('goods_number' => $order_stat['goods_number'], 
    										 	   'order_amount' => $order_stat['order_amount']));
    /* todo 记录日志 */
    $sn = $order['order_sn'];
    $sn .= ",总数量:$order_stat[goods_number],总金额:$order_stat[order_amount]";
    admin_log($sn, 'edit', 'scm_'.$order_type.'_goods');

    /* 跳回订单商品 */
    os_header("Location: scm.php?act=edit_goods&type=$order_type&id=$order_id");
    exit;	
}
/*------------------------------------------------------ */
//-- 提交更新单据商品
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='update_post_goods'){
    if (empty($_POST['order_id']) || !in_array($_POST['type'], array('purchase', 'enter', 'return', 'check')))
    {
        sys_msg('invalid param');
    }
    $order_id     = intval($_POST['order_id']);
    $order_type   = trim($_POST['type']);
    $order        = get_fast_scm_order_info($order_type, $order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	sys_msg(fast_scm_order_ur($order_type).'不存在或状态无效');
    }	
    update_scm_order_goods($order_type, $order_id, $_POST);  
    
    $order_stat = scm_order_amount($order_type, $order_id);
    /* 更新商品总金额和订单总金额 */
    update_scm_order($order_type, $order_id, array('goods_number' => $order_stat['goods_number'], 
    										 	   'order_amount' => $order_stat['order_amount']));
    /* todo 记录日志 */
    $sn = $order['order_sn'];
    $sn .= ",总数量:$order_stat[goods_number],总金额:$order_stat[order_amount]";
    admin_log($sn, 'edit', 'scm_'.$order_type.'_goods');

    /* 跳回订单商品 */
    os_header("Location: scm.php?act=edit_goods&type=$order_type&id=$order_id");
    exit;		
}
/*------------------------------------------------------ */
//-- 删除单据商品
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='remove_goods'){
	if(empty($_GET['order_id']) || !in_array($_GET['type'], array('purchase', 'enter', 'return', 'check'))){
        sys_msg('invalid param');			
	}
    $order_id     = intval($_GET['order_id']);
    $order_type   = trim($_GET['type']);
    $order        = get_fast_scm_order_info($order_type, $order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	sys_msg(fast_scm_order_ur($order_type).'不存在或状态无效');
    }  
	
	if(empty($_GET['goods_id']) && empty($_GET['rec_id'])){
        sys_msg('invalid param');		
	}	
	if(!empty($_GET['rec_id']) && $_GET['rec_id']>0){
		$db->query("DELETE FROM " . $os->table('scm_'.$order_type.'_goods') . " WHERE rec_id=" . intval($_GET['rec_id']));
	}else{
		$db->query("DELETE FROM " . $os->table('scm_'.$order_type.'_goods') . " WHERE order_id=$order_id AND goods_id=" . intval($_GET['goods_id']));
	}

    $order_stat = scm_order_amount($order_type, $order_id);
    /* 更新商品总金额和订单总金额 */
    update_scm_order($order_type, $order_id, array('goods_number' => $order_stat['goods_number'], 
    										 	   'order_amount' => $order_stat['order_amount']));
   	$sn = $order['order_sn'];
    admin_log($sn, 'remove', 'scm_'.$order_type.'_goods'); 										 
    /* 跳回订单商品 */
    os_header("Location: scm.php?act=edit_goods&type=$order_type&id=$order_id");
    exit;		
}
/*------------------------------------------------------ */
//-- 采购入库单列表
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='list_enter_order'){
    /* 检查权限 */
    admin_priv();    
    
    $smarty->assign('ur_here',      '采购入库单列表');   
	$smarty->assign('action_link',  array('text' => '添加采购入库单', 'href' => 'scm.php?act=add_enter_order'));      
    $smarty->assign('full_page',    1);
    
    $list = scm_enter_order_list();  
    $smarty->assign('status_list', 	            scm_order_status('enter'));    
    $smarty->assign('order_list', 	            $list['item']);    
    $smarty->assign('filter',        		    $list['filter']);
    $smarty->assign('page_count',    		    $list['page_count']); 
    $smarty->assign('record_count',  		    $list['record_count']);
    
    assign_query_info();
    $smarty->display('scm_enter_order_list.tpl');		
}
/*------------------------------------------------------ */
//-- 采购入库单翻页，排序
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='query_enter_order'){
    $list = scm_enter_order_list();
    $smarty->assign('order_list',              $list['item']);
    $smarty->assign('filter',         		   $list['filter']);
    $smarty->assign('record_count',   		   $list['record_count']);
    $smarty->assign('page_count',     		   $list['page_count']);
    
    make_json_result($smarty->fetch('scm_enter_order_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  	
}
/*------------------------------------------------------ */
//-- 添加、编辑采购入库单
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='add_enter_order' || $_REQUEST['act']=='edit_enter_order'){
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'add_enter_order';
    /* 权限检查 */
    $priv_str = $is_add ? 'add_scm_enter_order' : 'edit_scm_enter_order';
    admin_priv($priv_str);
    
    $smarty->assign('form_action', $is_add ? 'insert_enter_order' : 'update_enter_order');

    /* 初始化、取得采购订单信息 */
    if ($is_add)
    {
        $order = array(
            'order_id'    			    => 0,
            'order_sn'                  => create_fast_order_sn('enter'),
            'supplier_id'   		    => 0,        
            'depot_id'   			    => 0,
            'seat_id'      	            => 0,
            'discount'                  => 1,
            'formated_deliver_time'     => local_date('Y-m-d', local_strtotime('+1 months')),
            'order_brief'             	=> '',                              
            'formated_add_time'         => local_date('Y-m-d')
        );
    }
    else
    {
        if (empty($_GET['id']))
        {
            sys_msg('invalid param');
        }

        $id = intval($_GET['id']);
        $order = scm_enter_order_info($id);
        if (empty($order) || $order['order_status'] <> 0)
        {
            sys_msg('采购入库单不存在或状态无效');
        }
    }    

    $smarty->assign('order', $order);


    /* 显示模板 */
    if ($is_add)
    {
        $smarty->assign('ur_here', '添加采购入库单');
    }
    else
    {
        $smarty->assign('ur_here', '编辑采购入库单');
    }
    if ($is_add)
    {
        $href = 'scm.php?act=list_enter_order';
    }
    else
    {
        $href = 'scm.php?act=list_enter_order&' . list_link_postfix();
    }
    $smarty->assign('action_link', array('href' => $href, 'text' => '采购入库单列表'));
    
    assign_query_info();
    
    $smarty->display('scm_enter_order_edit.tpl');	
}
/*------------------------------------------------------ */
//-- 提交添加、编辑采购入库单
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='insert_enter_order' || $_REQUEST['act']=='update_enter_order'){
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert_enter_order';
    /* 权限检查 */
    
    $priv_str = $is_add ? 'add_scm_enter_order' : 'edit_scm_enter_order';
    admin_priv($priv_str);

    /* 提交值 */
    $order = array(
        'order_id'     			            => intval($_POST['id']),
        'order_sn'   		                => sub_str($_POST['order_sn'], 60, false),
		'supplier_id'   			        => intval($_POST['supplier_id']),        
		'depot_id'   			        	=> 0,
		'seat_id'      				        => 0,
		'discount'   						=> floatval($_POST['discount']),
		'deliver_time'         				=> local_strtotime($_POST['deliver_time']),
		'order_brief'    				    => trim($_POST['order_brief']),
		'add_time'         					=> local_strtotime($_POST['add_time'])
    );

    /* 判断单据编号是否重复 */
    if (!$exc_enter->is_only('order_sn', $order['order_sn'], $order['order_id']))
    {
        sys_msg('该单据编号已存在，请您换一个编号');
    }

    /* 保存采购订单信息 */
    if ($is_add)
    {
        $db->autoExecute($os->table('scm_enter_order'), $order, 'INSERT');
        $order['order_id'] = $db->insert_id();
    }
    else
    {
        $db->autoExecute($os->table('scm_enter_order'), $order, 'UPDATE', "order_id = '$order[order_id]'");
    }

    /* 记日志 */
    if ($is_add)
    {
        admin_log('采购入库单, 单号 ' . $order['order_sn'], 'add', 'scm_enter_order');
        $goto_act = 'edit_goods&type=enter';
    }
    else
    {
        admin_log('采购入库单, 单号 ' . $order['order_sn'], 'edit', 'scm_enter_order');
        $goto_act = 'info_enter_order';
    }

    /* 清除缓存 */
    clear_cache_files();

 	os_header("Location: scm.php?act=$goto_act&id=$order[order_id]");
	exit;	
}
/*------------------------------------------------------ */
//-- 删除采购入库单
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='remove_enter_order'){
    check_authz_json('drop_scm_enter_order');

    $order_id = intval($_GET['id']);
    $order = scm_enter_order_info($order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	if($_REQUEST['is_ajax']==1){
    		make_json_error('采购入库单不存在或状态无效');
    	}else{
    		sys_msg('采购入库单不存在或状态无效');
    	}
    	exit;
    }

    if($db->query("DELETE FROM " . $os->table('scm_enter_order') . " WHERE order_id='$order_id'")){
	    /* 记日志 */
	    admin_log(sprintf('采购入库单 s%', $order['order_sn']), 'remove', 'scm_enter_order');	
	    $db->query("DELETE FROM " . $os->table('scm_enter_goods') . " WHERE order_id='$order_id'");
    }

    /* 清除缓存 */
    clear_cache_files();
    
	if($_REQUEST['is_ajax']==1){
    	$url = 'scm.php?act=query_enter_order&' . str_replace('act=remove_enter_order', '', $_SERVER['QUERY_STRING']);
	}else{
		$url = 'scm.php?act=list_enter_order';
	}
    os_header("Location: $url\n");
    exit;		
}
/*------------------------------------------------------ */
//-- 查看采购入库单
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='info_enter_order'){
    if (empty($_GET['id']))
    {
        sys_msg('invalid param');
    }	
    $order_id = intval($_GET['id']);

    $order = scm_enter_order_info($order_id);
	if (empty($order))
	{
		die('采购入库单不存在');
	}
	
    $smarty->assign('ur_here', '查看采购入库单');
    $smarty->assign('action_link', array('href' => 'scm.php?act=list_enter_order', 'text' => '采购入库单列表'));	  
	
    $sql = "SELECT MAX(order_id) FROM " . $os->table('scm_enter_order') . " WHERE order_id < '$order[order_id]'";    
    $smarty->assign('prev_id', $db->getOne($sql));
    $sql = "SELECT MIN(order_id) FROM " . $os->table('scm_enter_order') . " WHERE order_id > '$order[order_id]'";
    $smarty->assign('next_id', $db->getOne($sql)); 
    
	$smarty->assign('order', $order);
	
	$goods_list = scm_order_goods('enter', $order_id);
	
	$smarty->assign('goods_list', $goods_list);

	/* 取得订单操作记录 */
	$smarty->assign('action_list', scm_order_action('enter', $order_id));
	
    assign_query_info();    
        	
    $smarty->display('scm_enter_order_info.tpl');  	
}

elseif($_REQUEST['act']=='check_enter_order'){
	/* 检查权限 */
	admin_priv('check_enter_order');

    if (empty($_REQUEST['id']))
    {
        sys_msg('invalid param');
    }	
    $order_id   = intval($_REQUEST['id']);
    $goods_barcode   = trim($_REQUEST['goods_barcode']);
    $order = scm_enter_order_info($order_id);
	if (empty($order))
	{
		die('采购入库单不存在');
	}
	if($order['goods_number']<=0){
		sys_msg('采购入库单没有商品不能做任何操作');		
	}
    if(!empty($_REQUEST['is_submit']) && $_REQUEST['is_submit']=='yes_submit'){
    	$result = barcode_generate_check_goods('enter', $order_id, $goods_barcode, $order);
    	if($result==FALSE){
	     	$identify_schemes = get_barcode_identify_schemes(); 	
	    	barcode_identify_check_goods($identify_schemes, 'enter', $order_id, $goods_barcode, $order);   		
    	}
    	$is_check = $db->getOne("SELECT SUM(goods_number)=SUM(send_number) FROM " . 
    							$os->table('scm_enter_goods') . " WHERE order_id=$order_id");
    	if($is_check && $is_check==1){
    		$db->query("UPDATE " . $os->table('scm_enter_order') . " SET order_status=1 WHERE order_id=$order_id");
    		update_scm_order_action('enter', $order['order_sn'], 1, "恭喜你，采购入库单 [ $order[order_sn] ] 扫描验收通过");
    	}
    }
	/* 模板赋值 */
	$smarty->assign('ur_here', '扫描验收采购入库单');

	$smarty->assign('action_link', array('href' => 'scm.php?act=list_enter_order', 'text' => '采购入库单列表'));	  

	$smarty->assign('full_page',        1);
	
    $smarty->assign('order', $order);
    
    $goods_list = check_enter_goods_list($order_id);
    $smarty->assign('goods_list', $goods_list);
        
	/* 显示模板 */
	assign_query_info();

	$smarty->display('scm_enter_order_check.tpl');
}
/*------------------------------------------------------ */
//-- 操作采购入库单状态（载入页面）
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='operate_enter_order'){
    if (empty($_POST['order_id']))
    {
        sys_msg('invalid param');
    }	
    $order_id   = intval($_POST['order_id']);
    $order = scm_enter_order_info($order_id);
	if (empty($order))
	{
		die('采购入库单不存在');
	}
	if($order['goods_number']<=0){
		sys_msg('采购入库单没有商品不能做任何操作');		
	}
    $action_note = empty($_POST['action_note']) ? '' : trim($_POST['action_note']);
    $goto_act    = "info_enter_order&id=$order_id";
    
    if (isset($_POST['storage']))
    {
        if($order['order_status']<>1){
    		sys_msg('无效状态无法入库');
    	}
    	if(FALSE===alter_storage('enter', $order_id)){
    		sys_msg('入库失败');exit;
    	}
        $operation      = 'order_status';
        $order_status   = 2;
    }

    if (isset($_POST['balance']))
    {
        if($order['order_status']<>2){
    		sys_msg('无效状态无法结算');
    	}    	
    	$goto_act = "add_balance_order&type=enter_order&id=$order_id";  	
    }

    if (isset($_POST['disaffirm']))
    {
     	if($order['order_status']<>0){
    		sys_msg('无效状态无法作废');
    	}
        $operation      = 'order_status';
        $order_status   = 4;
    }
    
    update_scm_order('enter', $order_id, array($operation => $order_status));
	update_scm_order_action('enter', $order['order_sn'], $order_status, $action_note);
    os_header("Location: scm.php?act=$goto_act");
    exit;	
}

elseif($_REQUEST['act']=='list_return_order'){
     /* 检查权限 */
    admin_priv();    
    
    $smarty->assign('ur_here',      '采购退货单列表');   
	$smarty->assign('action_link',  array('text' => '添加采购退货单', 'href' => 'scm.php?act=add_return_order'));      
    $smarty->assign('full_page',    1);
    
    $list = scm_return_order_list();  
    $smarty->assign('status_list', 	            scm_order_status('return'));    
    $smarty->assign('order_list', 	            $list['item']);    
    $smarty->assign('filter',        		    $list['filter']);
    $smarty->assign('page_count',    		    $list['page_count']); 
    $smarty->assign('record_count',  		    $list['record_count']);
    
    assign_query_info();
    $smarty->display('scm_return_order_list.tpl');		
}

elseif($_REQUEST['act']=='query_return_order'){
    $list = scm_return_order_list();
    $smarty->assign('order_list',              $list['item']);
    $smarty->assign('filter',         		   $list['filter']);
    $smarty->assign('record_count',   		   $list['record_count']);
    $smarty->assign('page_count',     		   $list['page_count']);
    
    make_json_result($smarty->fetch('scm_return_order_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  	
}

elseif($_REQUEST['act']=='info_return_order'){
    if (empty($_GET['id']))
    {
        sys_msg('invalid param');
    }	
    $order_id = intval($_GET['id']);
    
    $order = scm_return_order_info($order_id);
	if (empty($order))
	{
		sys_msg('采购退货单不存在');
	}
	
    $smarty->assign('ur_here', '查看采购退货单');
    $smarty->assign('action_link', array('href' => 'scm.php?act=list_return_order', 'text' => '采购退货单列表'));
	
    $sql = "SELECT MAX(order_id) FROM " . $os->table('scm_return_order') . " WHERE order_id < '$order[order_id]'";    
    $smarty->assign('prev_id', $db->getOne($sql));
    $sql = "SELECT MIN(order_id) FROM " . $os->table('scm_return_order') . " WHERE order_id > '$order[order_id]'";
    $smarty->assign('next_id', $db->getOne($sql)); 
    
	$smarty->assign('order', $order);
	
	$goods_list = scm_order_goods('return', $order_id);
	
	$smarty->assign('goods_list', $goods_list);
		
	$smarty->assign('action_list', scm_order_action('return', $order_id));
	
    assign_query_info();    
        	 
    $smarty->display('scm_return_order_info.tpl');	
}

elseif($_REQUEST['act']=='add_return_order' || $_REQUEST['act']=='edit_return_order'){
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'add_return_order';
    /* 权限检查 */
    $priv_str = $is_add ? 'add_scm_return_order' : 'edit_scm_return_order';
    admin_priv($priv_str);
    
    $smarty->assign('form_action', $is_add ? 'insert_return_order' : 'update_return_order');

    /* 初始化、取得采购退货单信息 */
    if ($is_add)
    {
        $order = array(
            'order_id'                  => 0,
            'order_sn'   	            => create_fast_order_sn('return'),
            'supplier_id'   		    => 0,        
            'depot_id'   			    => 0,
            'seat_id'      	            => 0,
            'discount'                  => 1,
            'formated_deliver_time'     => local_date('Y-m-d', local_strtotime('+1 months')),
            'order_brief'               => '',                              
            'formated_add_time'         => local_date('Y-m-d')
        );
    }
    else
    {
        if (empty($_GET['id']))
        {
            sys_msg('invalid param');
        }

        $id = intval($_GET['id']);
        $order = scm_return_order_info($id);
        if (empty($order) || ($order['order_status']<>0 && $order['order_status']<>2))
        {
            sys_msg('采购退货单不存在或状态无效');
        }
    }    

    $smarty->assign('order', $order);


    /* 显示模板 */
    if ($is_add)
    {
        $smarty->assign('ur_here', '添加采购退货单');
    }
    else
    {
        $smarty->assign('ur_here', '编辑采购退货单');
    }
    if ($is_add)
    {
        $href = 'scm.php?act=list_return_order';
    }
    else
    {
        $href = 'scm.php?act=list_return_order&' . list_link_postfix();
    }
    $smarty->assign('action_link', array('href' => $href, 'text' => '采购退货单列表'));
    
    assign_query_info();    
    $smarty->display('scm_return_order_edit.tpl'); 	
}

elseif ($_REQUEST['act'] == 'insert_return_order' || $_REQUEST['act'] == 'update_return_order')
{
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert_return_order';
    /* 权限检查 */
	$priv_str = $is_add ? 'add_scm_return_order' : 'edit_scm_return_order';
    admin_priv($priv_str);

    /* 提交值 */
    $order = array(
        'order_id'     			            => intval($_POST['id']),
        'order_sn'   			            => sub_str($_POST['order_sn'], 60, false),
		'supplier_id'   			        => intval($_POST['supplier_id']),        
		'depot_id'   			        	=> 0,
		'seat_id'      				        => 0,
		'discount'   						=> floatval($_POST['discount']),
		'deliver_time'         				=> local_strtotime($_POST['deliver_time']),
		'order_brief'    				    => trim($_POST['order_brief']),
		'add_time'         					=> local_strtotime($_POST['add_time'])
    );

    if(!$is_add){
        $return_order = scm_return_order_info($order['order_id']);
        if (empty($return_order) || ($return_order['order_status']<>0 && $return_order['order_status']<>2))
        {
            sys_msg('采购退货单不存在或状态无效');
        }  	
    }
    
    /* 判断单据编号是否重复 */
    if (!$exc_return->is_only('order_sn', $order['order_sn'], $order['order_id']))
    {
        sys_msg('该单据编号已存在，请您换一个编号');
    }

    /* 保存采购订单信息 */
    if ($is_add)
    {
        $db->autoExecute($os->table('scm_return_order'), $order, 'INSERT');
        $order['order_id'] = $db->insert_id();
    }
    else
    {
        $db->autoExecute($os->table('scm_return_order'), $order, 'UPDATE', "order_id = '$order[order_id]'");
    }

    /* 记日志 */
    if ($is_add)
    {
        admin_log('采购退货单, 单号 ' . $order['order_sn'], 'add', 'scm_return_order');
        $goto_act = 'edit_goods&type=return';
    }
    else
    {
        admin_log('采购退货单, 单号 ' . $order['order_sn'], 'edit', 'scm_return_order');
        $goto_act = 'info_return_order';
    }

    /* 清除缓存 */
    clear_cache_files();

 	os_header("Location: scm.php?act=$goto_act&id=$order[order_id]");
	exit;
}

elseif($_REQUEST['act']=='remove_return_order'){

    check_authz_json('drop_scm_return_order');

    $order_id = intval($_GET['id']);
    $order = scm_return_order_info($order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	if($_REQUEST['is_ajax']==1){
    		make_json_error('采购退货单不存在或状态无效');
    	}else{
    		sys_msg('采购退货单不存在或状态无效');
    	}
    	exit;
    }

    if($db->query("DELETE FROM " . $os->table('scm_return_order') . " WHERE order_id='$order_id'")){
	    /* 记日志 */
	    admin_log(sprintf('采购退货单 s%', $order['order_sn']), 'remove', 'scm_return_order');	
	    $db->query("DELETE FROM " . $os->table('scm_return_goods') . " WHERE order_id='$order_id'");
    }

    /* 清除缓存 */
    clear_cache_files();
    if($_REQUEST['is_ajax']==1){
    	$url = 'scm.php?act=query_return_order&' . str_replace('act=remove_return_order', '', $_SERVER['QUERY_STRING']);
    }else{
    	$url = 'scm.php?act=list_return_order';
    }
    os_header("Location: $url\n");
    exit;		
}

elseif($_REQUEST['act']=='check_return_order'){
	/* 检查权限 */
	admin_priv('check_return_order');

    if (empty($_REQUEST['id']))
    {
        sys_msg('invalid param');
    }	
    $order_id   = intval($_REQUEST['id']);
    $goods_barcode   = trim($_REQUEST['goods_barcode']);
    $order = scm_return_order_info($order_id);
	if (empty($order))
	{
		die('采购退货单不存在');
	}
	if($order['goods_number']<=0){
		sys_msg('采购退货单没有商品不能做任何操作');		
	}
    if(!empty($_REQUEST['is_submit']) && $_REQUEST['is_submit']=='yes_submit'){
    	$result = barcode_generate_check_goods('return', $order_id, $goods_barcode, $order);
    	if($result==FALSE){
	     	$identify_schemes = get_barcode_identify_schemes(); 	
	    	barcode_identify_check_goods($identify_schemes, 'return', $order_id, $goods_barcode, $order);   		
    	}        
    	$is_check = $db->getOne("SELECT SUM(goods_number)=SUM(send_number) FROM " . 
    							$os->table('scm_return_goods') . " WHERE order_id=$order_id");
    	if($is_check && $is_check==1){
    		$db->query("UPDATE " . $os->table('scm_return_order') . " SET order_status=1 WHERE order_id=$order_id");
			update_scm_order_action('return', $order['order_sn'], 1, "恭喜你，采购退货单 [ $order[order_sn] ] 扫描验收通过");    		
    	}
    }
	/* 模板赋值 */
	$smarty->assign('ur_here', '扫描验收采购退货单');

	$smarty->assign('action_link', array('href' => 'scm.php?act=list_return_order', 'text' => '采购退货单列表'));	  

	$smarty->assign('full_page',        1);
	
    $smarty->assign('order', $order);
    
    $goods_list = check_return_goods_list($order_id);
    $smarty->assign('goods_list', $goods_list);
        
	/* 显示模板 */
	assign_query_info();

	$smarty->display('scm_return_order_check.tpl');
}

elseif($_REQUEST['act']=='operate_return_order'){
    if (empty($_POST['order_id']))
    {
        sys_msg('invalid param');
    }	
    $order_id   = intval($_POST['order_id']);
    $order = scm_return_order_info($order_id);
	if (empty($order))
	{
		die('采购退货单不存在');
	}
	if($order['goods_number']<=0){
		sys_msg('采购入库单没有商品不能做任何操作');		
	}
    $action_note = empty($_POST['action_note']) ? '' : trim($_POST['action_note']);
    $goto_act = "info_return_order&id=$order_id";
    
    if (isset($_POST['outstorage']))
    {
        if($order['order_status']<>1){
    		sys_msg('无效状态无法出库');
    	}
    	if(FALSE===alter_storage('return', $order_id, FALSE)){
    		sys_msg('操作库存失败');exit;
    	}	
        $operation      = 'order_status';
        $order_status   = 2;
    }
        
    if (isset($_POST['balance']))
    {
        if($order['order_status']<>2){
    		sys_msg('无效状态无法结算');
    	}    	
    	$goto_act = "add_balance_order&type=return_order&id=$order_id"; 
	    os_header("Location: scm.php?act=$goto_act");
	    exit;
    }

    if (isset($_POST['disaffirm']))
    {
     	if($order['order_status']<>0){
    		sys_msg('无效状态无法作废');
    	}
        $operation      = 'order_status';
        $order_status   = 4;
    }
    
    update_scm_order('return', $order_id, array($operation => $order_status));
	update_scm_order_action('return', $order['order_sn'], $order_status, $action_note);
    os_header("Location: scm.php?act=$goto_act");
    exit;	
}

elseif($_REQUEST['act']=='add_balance_order'){
	$order_id = intval($_GET['id']);
    $order = array();
	$order_list = array();
        
    switch ($_GET['type']){
    	case 'enter_order':
    		$order = scm_enter_order_info($order_id);
            $payed_amount = $db->getOne("SELECT SUM(d.pay_amount) FROM " . $os->table('scm_balance_detail') . 
    						" d JOIN " . $os->table('scm_balance_order') . " o ON d.order_id=o.order_id WHERE " . 
    						" o.order_status=1 AND d.order_type=1 AND d.from_order_id=" . intval($order['order_id']));   
    	    $order['order_type']	    		= 	 	1;
    		$order['formated_payed_amount']	    = 		price_format(abs($payed_amount), false);					
    		$order_list[] 						= 		$order;    		
    		break;
    	case 'return_order':
     		$order = scm_return_order_info($order_id);
            $payed_amount = $db->getOne("SELECT SUM(d.pay_amount) FROM " . $os->table('scm_balance_detail') . 
    						" d JOIN " . $os->table('scm_balance_order') . " o ON d.order_id=o.order_id WHERE " . 
    						" o.order_status=1 AND d.order_type=2 AND d.from_order_id=" . intval($order['order_id']));   
    	    $order['order_type']	    		= 	 	2;
    	    $order['goods_number']	    		= 	 	'-' . $order['goods_number'];
			$order['formated_order_amount']     =       price_format('-'.$order['order_amount'], false);
    		$order['formated_payed_amount']	    = 		price_format($payed_amount, false);					
    		$order_list[] 						= 		$order;    	   		
    		break;
    }	
    
    $order['order_sn']       				= 	create_fast_order_sn('balance');
    $order['deliver_time']   				= 	local_date('Y-m-d');
    $order['pay_type_list']  				= 	get_pays_list();
    $order['balance_type']  				= 	-1;
    $order['order_amount']                  =   0;
    
    if(in_array($_GET['type'], array('enter_order', 'return_order'))){
    		$order['balance_type'] 				= 		0;
    		$order['is_alone'] 					= 		1;    	
    }
    
    $smarty->assign('ur_here',      '添加采购结算单');   
    $smarty->assign('action_link',  array('text' => '采购结算单列表', 'href' => 'scm.php?act=list_balance_order'));    
    $smarty->assign('full_page',    1);  
    $smarty->assign('order', $order);
    $smarty->assign('order_list', 	            $order_list);    
    $smarty->assign('filter',        		    array());
    $smarty->assign('page_count',    		    0); 
    $smarty->assign('record_count',  		    0);   
    	
    assign_query_info();
    
    $smarty->display('scm_balance_order_edit.tpl'); 		
}

elseif($_REQUEST['act']=='search_balance_order'){
    $list = query_balance_order();
    $smarty->assign('order_list',              $list['item']);
    $smarty->assign('filter',         		   $list['filter']);
    $smarty->assign('record_count',   		   $list['record_count']);
     
    make_json_result($smarty->fetch('scm_balance_order_edit.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  		
}

elseif($_REQUEST['act']=='get_balance_amount'){
	$order_type = intval($_REQUEST['order_type']);
	$order_id = intval($_REQUEST['order_id']);
	$pay_amount = floatval($_REQUEST['pay_amount']);
    if($order_type==1){
    	$all_amount = $db->getOne("SELECT order_amount FROM " . $os->table('scm_enter_order') . " WHERE order_id=$order_id");
    }elseif($order_type==2){
    	$all_amount = $db->getOne("SELECT concat('-',order_amount) FROM " . $os->table('scm_return_order') . " WHERE order_id=$order_id"); 
    }

    $payed_amount = $db->getOne("SELECT SUM(d.pay_amount) FROM " . $os->table('scm_balance_detail') . 
					" d JOIN " . $os->table('scm_balance_order') . " o ON d.order_id=o.order_id WHERE " . 
					" o.order_status=1 AND d.order_type='$order_type' AND d.from_order_id='$order_id'");     							
    $surplus_amount = floatval($all_amount)-floatval($payed_amount);
    if($order_type==2 && $pay_amount>=0){
    	$res['error'] = 1;
    	$res['message'] = '必须正确填写本次结算金额';    	
    }
    if($order_type==1&& $pay_amount<=0){
    	$res['error'] = 1;
    	$res['message'] = '必须正确填写本次结算金额';    	
    }
    if($order_type==1 && ($pay_amount > $surplus_amount)){
    	$res['error'] = 1;
    	$res['message'] = '必须正确填写本次结算金额';
    }
    if($order_type==2 && ($pay_amount < $surplus_amount)){
    	$res['error'] = 1;
    	$res['message'] = '必须正确填写本次结算金额';
    }    
	make_json_result('', '', $res);
}

elseif($_REQUEST['act']=='update_balance_order'){
    if(!is_numeric($_POST['pay_amount']) || !is_numeric($_POST['order_amount']))
    {
        sys_msg('单据性质参数不正确', 1);    	    
    }
    if($_POST['pay_amount'] < $_POST['order_amount'])
    {
    	sys_msg('支付金额不能小于结算金额', 1);    
    }
    $order_amount  = !empty($_POST['order_amount']) ? floatval($_POST['order_amount']) : 0;
    $pay_amount    = !empty($_POST['pay_amount']) ? floatval($_POST['pay_amount']) : 0;
    $order_type    = !empty($_POST['alone_order_type']) ? intval($_POST['alone_order_type']) : 0;
    $from_order_id = !empty($_POST['alone_order_id']) ? intval($_POST['alone_order_id']) : 0;
    if(!isset($_POST['balance_type']) || !in_array($_POST['balance_type'], array(0,1)))
    {
     	sys_msg('结算类型不正确', 1);    	
    }
    if($_POST['balance_type']!=1 && (empty($_POST['checkboxes']) || !is_array($_POST['checkboxes'])))
    {
        sys_msg('没有选定单据', 1);
    }
    if($_POST['balance_type']!=1 && (empty($_POST['order_types']) || !is_array($_POST['order_types'])))
    {
        sys_msg('单据性质参数丢失', 1);    	
    }	
    $res = $db->query("INSERT INTO ".$os->table('scm_balance_order')."(order_sn,supplier_id,deliver_time,order_amount,pay_amount,
    			surplus_amount,pay_type,order_status,balance_type,order_brief,add_time,order_type,from_order_id) VALUES('".$_POST['order_sn'].
    			"',".intval($_POST['supplier_id']).",".local_strtotime($_POST['deliver_time']).",0,".floatval($_POST['pay_amount']).
    			",0,".intval($_POST['pay_type']).",0,".intval($_POST['balance_type']).",'',".gmtime().",$order_type,$from_order_id)");
    if($res!==false)
    {
    	$order_id = $db->insert_id();
    }
    if($order_id <= 0)
    {
    	sys_msg('添加结算单失败', 1); 
    }

    if($_POST['balance_type'] != 1)
    {
	    $arr_ids = array();
	    foreach($_POST['checkboxes'] as $k=>$id)
	    {
	    	if(!in_array($_POST['order_types'][$k], array(1, 2))) continue;
	    	if(empty($_POST['pay_amounts'][$k]) || !is_numeric($_POST['pay_amounts'][$k])) continue;    
            $payed_amount = $db->getOne("SELECT SUM(d.pay_amount) FROM " . $os->table('scm_balance_detail') . " d JOIN " . 
                            $os->table('scm_balance_order') . " o ON d.order_id=o.order_id WHERE o.order_status=1 AND " . 
                            " d.order_type=".intval($_POST['order_types'][$k])." AND d.from_order_id=".intval($order['order_id']));
	        $tb = sprintf('scm_%s_order', ($_POST['order_types'][$k]==2) ? 'return' : 'enter');
	        $order_amt_str = ($_POST['order_types'][$k]==2) ? "concat('-',order_amount)" : 'order_amount';
	    	$db->query("INSERT INTO ".$os->table('scm_balance_detail')."(order_id,order_type,from_order_id,associate_time,
	    	           order_amount,payed_amount,pay_amount,surplus_amount,order_brief,add_time) SELECT $order_id," . 
	    	           intval($_POST['order_types'][$k]) . ",order_id,add_time,$order_amt_str," . floatval($payed_amount) . 
	    	           "," . floatval($_POST['pay_amounts'][$k]) . ",$order_amt_str-" . floatval($payed_amount) . "-" . 
	    	           floatval($_POST['pay_amounts'][$k]) . ",''," . gmtime() . " FROM " . $os->table($tb) . 
	    	           " WHERE order_id=" . intval($id));
	    }
	    
	    $order_amount = get_balance_amount($order_id);
    }
    update_scm_order('balance', $order_id, array('order_amount'   => $order_amount, 
    										     'surplus_amount' => $pay_amount - $order_amount));
    										         										        										         
    /* 清除缓存 */
    clear_cache_files();

    $links = array(
        array('href' => "scm.php?act=add_balance_order", 'text' => '继续添加新的采购结算单'),
        array('href' => "scm.php?act=list_balance_order", 'text' => '返回采购结算单列表')
    );
    sys_msg('采购结算单添加成功', 0, $links);
	exit;    
}

elseif($_REQUEST['act']=='list_balance_order'){
     /* 检查权限 */
    admin_priv();    
    
    $smarty->assign('ur_here',      '采购结算单列表');   
	$smarty->assign('action_link',  array('text' => '添加采购结算单', 'href' => 'scm.php?act=add_balance_order'));      
    $smarty->assign('full_page',    1);
    
    $list = scm_balance_order_list();  
    $smarty->assign('status_list', 	            scm_order_status('balance'));  
    $smarty->assign('pay_type_list', 	        get_pays_list());    
    $smarty->assign('order_list', 	            $list['item']);    
    $smarty->assign('filter',        		    $list['filter']);
    $smarty->assign('page_count',    		    $list['page_count']); 
    $smarty->assign('record_count',  		    $list['record_count']);
    
    assign_query_info();
    $smarty->display('scm_balance_order_list.tpl');	
}

elseif($_REQUEST['act']=='query_balance_order'){
    $list = scm_balance_order_list();
    $smarty->assign('order_list',              $list['item']);
    $smarty->assign('filter',         		   $list['filter']);
    $smarty->assign('record_count',   		   $list['record_count']);
    $smarty->assign('page_count',     		   $list['page_count']);
    
    make_json_result($smarty->fetch('scm_balance_order_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  
}

elseif($_REQUEST['act']=='remove_balance_order'){
    check_authz_json('drop_scm_balance_order');

    $order_id = intval($_GET['id']);
    $order = scm_balance_order_info($order_id);
    if(empty($order)){
    	make_json_error('采购结算单不存在');
    	exit;
    }
    if($order['order_status'] <> 0){
    	make_json_error('采购结算单已处理不能删除');
    	exit;    	
    }
    if($db->query("DELETE FROM " . $os->table('scm_balance_order') . " WHERE order_id='$order_id'")){
	    /* 记日志 */
	    admin_log(sprintf('采购结算单 s%', $order['order_sn']), 'remove', 'scm_balance_order');	
	    $db->query("DELETE FROM " . $os->table('scm_balance_detail') . " WHERE order_id='$order_id'");	    
    }

    /* 清除缓存 */
    clear_cache_files();

    $url = 'scm.php?act=query_balance_order&' . str_replace('act=remove_balance_order', '', $_SERVER['QUERY_STRING']);

    os_header("Location: $url\n");
    exit;	
}

elseif($_REQUEST['act']=='info_balance_order'){
    if (empty($_GET['id']))
    {
        sys_msg('invalid param');
    }	
    $order_id = intval($_GET['id']);

    $smarty->assign('ur_here', '查看采购结算单');
    $smarty->assign('action_link', array('href' => 'scm.php?act=list_balance_order', 'text' => '采购结算单列表'));	  
        
    $order = scm_balance_order_info($order_id);
	if (empty($order))
	{
		die('采购结算单不存在');
	}
	$order['pay_type_list']  				= 	get_pays_list();
    $sql = "SELECT MAX(order_id) FROM " . $os->table('scm_balance_order') . " WHERE order_id < '$order[order_id]'";    
    $smarty->assign('prev_id', $db->getOne($sql));
    $sql = "SELECT MIN(order_id) FROM " . $os->table('scm_balance_order') . " WHERE order_id > '$order[order_id]'";
    $smarty->assign('next_id', $db->getOne($sql)); 
    
	$smarty->assign('order', $order);
	
	$order_list = scm_balance_detail($order_id);
	$smarty->assign('order_list', $order_list);
		
	$smarty->assign('action_list', scm_order_action('balance', $order_id));
	
    assign_query_info();    
        	 
    $smarty->display('scm_balance_order_info.tpl');
}

elseif($_REQUEST['act']=='remove_balance_detail'){
	$order_id      = intval($_GET['order_id']);	
    $order = scm_balance_order_info($order_id);
	if (empty($order))
	{
		die('采购结算单不存在');
	}
	if ($order['order_status']<>0)
	{
		die('无效状态无法删除采购结算单');
	}	
	$order_type    = intval($_GET['order_type']);
	$from_order_id = intval($_GET['from_order_id']);
	$pay_amount    = $db->getOne("SELECT pay_amount FROM ".$os->table('scm_balance_order')." WHERE order_id='$order_id'");
	$sql = "DELETE FROM " . $GLOBALS['os']->table('scm_balance_detail') . " WHERE order_id='$order_id' AND " . 
	       " order_type='$order_type' AND from_order_id='$from_order_id'";
	$GLOBALS['db']->query($sql);
    
	$order_amount = get_balance_amount($order_id);
    update_scm_order('balance', $order_id, array('order_amount'   => $order_amount, 
    										     'surplus_amount' => $pay_amount - $order_amount));	
    os_header("Location: scm.php?act=info_balance_order&id=$order_id");
    exit;									     
}

elseif($_REQUEST['act']=='operate_balance_order'){
    if (empty($_POST['order_id']))
    {
        sys_msg('invalid param');
    }	
    $order_id   = intval($_POST['order_id']);
    $order = scm_balance_order_info($order_id);
    if(empty($order)){
		sys_msg('采购结算单不存在');
    }
    
    $action_note = empty($_POST['action_note']) ? '' : trim($_POST['action_note']);
    
    if (isset($_POST['confirm']))
    {
        if($order['order_status'] <> 0){
    		sys_msg('无效状态无法确认');
    	}  
    	$order_amount = 0;
    	$pay_order_amount   = floatval($_POST['pay_amount']);
	    if($_POST['balance_type'] != 1)
	    {
		    $arr_ids = array();
		    foreach($_POST['order_ids'] as $k=>$id)
		    {
		    	if(!in_array($_POST['order_types'][$k], array(1, 2))) continue;
		    	$order_type = intval($_POST['order_types'][$k]);
		    	if(empty($_POST['pay_amounts'][$k]) || !is_numeric($_POST['pay_amounts'][$k])) continue;  
		    	$pay_amount = floatval($_POST['pay_amounts'][$k]);
		    	$sql = "UPDATE ".$os->table('scm_balance_detail')." SET pay_amount='$pay_amount'," . 
		    	       "surplus_amount=order_amount-payed_amount-$pay_amount WHERE order_id='$order_id' " . 
		    	       " AND order_type='$order_type' AND from_order_id='$id'";
		    	$db->query($sql);
		    }
		    
		    $order_amount = get_balance_amount($order_id);
		    if($pay_order_amount<$order_amount){
		    	sys_msg('支付金额不能小于结算金额');
		    }
	    }
	    
 
        update_scm_order('balance', $order_id, array('pay_amount'     => $pay_amount,
                                                     'order_amount'   => $order_amount, 
    										         'surplus_amount' => ($pay_amount - $order_amount),
    										         'order_brief'    => trim($_POST['order_brief'])));	
        $operation      = 'order_status';
        $order_status   = 1;
    }
    
    if (isset($_POST['balance']))
    {
        if($order['order_status'] <> 1){
    		sys_msg('无效状态无法结算');
    	}
        $operation      = 'order_status';
        $order_status   = 2;
    }

    if (isset($_POST['disaffirm']))
    {
        if($order['order_status'] <> 0){
    		sys_msg('无效状态无法作废');
    	}
        $operation      = 'order_status';
        $order_status   = 3;
    }
    update_scm_order('balance', $order_id, array($operation => $order_status));
	update_scm_order_action('balance', $order['order_sn'], $order_status, $action_note);
    os_header("Location: scm.php?act=info_balance_order&id=$order_id");
    exit;	
}
/*------------------------------------------------------ */
//-- 支付方式列表
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='list_payment'){
     /* 检查权限 */
    admin_priv();    
    
    $smarty->assign('ur_here',      '支付方式列表');   
	$smarty->assign('action_link',  array('text' => '添加支付方式', 'href' => 'scm.php?act=add_payment'));      
    $smarty->assign('full_page',    1);
    
    $list = scm_payment_list();  
    $smarty->assign('payment_list', 	        $list['item']);    
    $smarty->assign('filter',        		    $list['filter']);
    $smarty->assign('page_count',    		    $list['page_count']); 
    $smarty->assign('record_count',  		    $list['record_count']);
    
    assign_query_info();
    $smarty->display('scm_payment_list.tpl');		
}
/*------------------------------------------------------ */
//-- 支付方式翻页，排序
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='query_payment'){
	
    $list = scm_payment_list();
    $smarty->assign('payment_list',         $list['item']);
    $smarty->assign('filter',         		$list['filter']);
    $smarty->assign('record_count',   		$list['record_count']);
    $smarty->assign('page_count',     		$list['page_count']);
    
    make_json_result($smarty->fetch('scm_payment_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  
}
/*------------------------------------------------------ */
//-- 添加、编辑支付方式
/*------------------------------------------------------ */
elseif($_REQUEST['act'] == 'add_payment' || $_REQUEST['act'] == 'edit_payment'){
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'add_payment';
    /* 权限检查 */
    $priv_str = $is_add ? 'add_scm_payment' : 'edit_scm_payment';
    admin_priv($priv_str);
    
    $smarty->assign('form_action', $is_add ? 'insert_payment' : 'update_payment');

    /* 初始化、取得办事处信息 */
    if ($is_add)
    {
        $pay = array(
            'pay_id'     		=> 0,
            'pay_name'   		=> '',
            'pay_code'          => '',
            'pay_accounts'   	=> '',
            'is_show'   		=> 1
        );
    }
    else
    {
        if (empty($_GET['id']))
        {
            sys_msg('invalid param');
        }

        $id = intval($_GET['id']);
        $sql = "SELECT * FROM " . $os->table('scm_payment') . " WHERE pay_id = '$id'";
        $pay = $db->getRow($sql);
        if (empty($pay))
        {
            sys_msg('支付方式不存在');
        }
    }


    $smarty->assign('pay', $pay);


    /* 显示模板 */
    if ($is_add)
    {
        $smarty->assign('ur_here', '添加支付方式');
    }
    else
    {
        $smarty->assign('ur_here', '编辑支付方式');
    }
    if ($is_add)
    {
        $href = 'scm.php?act=list_payment';
    }
    else
    {
        $href = 'scm.php?act=list_payment&' . list_link_postfix();
    }
    $smarty->assign('action_link', array('href' => $href, 'text' => '支付方式列表'));
    
    assign_query_info();
    
    $smarty->display("scm_payment_info.tpl");   	
}
/*------------------------------------------------------ */
//-- 提交添加、编辑支付方式
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'insert_payment' || $_REQUEST['act'] == 'update_payment'){
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert_payment';
    /* 权限检查 */
    $priv_str = $is_add ? 'add_scm_payment' : 'edit_scm_payment';
    admin_priv($priv_str);

    /* 提交值 */
    $pay = array(
        'pay_id'         => intval($_POST['id']),
        'pay_name'       => sub_str($_POST['pay_name'], 0),
        'pay_code'       => sub_str($_POST['pay_code'], 0),
        'pay_accounts'   => sub_str($_POST['pay_accounts'], 0),
        'is_show'        => !empty($_POST['is_show']) ? intval($_POST['is_show']) : 0
    );

    /* 判断名称是否重复 */
    if (!$exc_pay->is_only('pay_name', $pay['pay_name'], $pay['pay_id']))
    {
        sys_msg('该支付名称已存在，请您换一个名称');
    }
    
    if (!$exc_pay->is_only('pay_code', $pay['pay_code'], $pay['pay_id']))
    {
        sys_msg('该支付代码已存在，请您换一个代码');
    }
    /* 保存供应商类型信息 */
    if ($is_add)
    {
        $db->autoExecute($os->table('scm_payment'), $pay, 'INSERT');
        $pay['pay_id'] = $db->insert_id();
    }
    else
    {
        $db->autoExecute($os->table('scm_payment'), $pay, 'UPDATE', "pay_id = '$pay[pay_id]'");
    }
    /* 记日志 */
    if ($is_add)
    {
        admin_log($pay['pay_name'], 'add', 'scm_payment');
    }
    else
    {
        admin_log($pay['pay_name'], 'edit', 'scm_payment');
    }

    /* 清除缓存 */
    clear_cache_files();

    /* 提示信息 */
    if ($is_add)
    {
        $links = array(
            array('href' => 'scm.php?act=add_payment', 'text' => '继续添加新的支付方式'),
            array('href' => 'scm.php?act=list_payment', 'text' => '返回支付方式列表')
        );
        sys_msg('添加支付方式成功', 0, $links);
    }
    else
    {
        $links = array(
            array('href' => 'scm.php?act=list_payment&' . list_link_postfix(), 'text' => '返回支付方式列表')
        );
        sys_msg('编辑支付方式成功', 0, $links);
    }	
}
/*------------------------------------------------------ */
//-- 删除支付方式
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='remove_payment'){
    check_authz_json('drop_scm_payment');

    $pay_id   = intval($_GET['id']);
    $pay = $db->getRow("SELECT pay_name, is_system FROM " . $os->table('scm_payment') . " WHERE pay_id='$pay_id'"); 
    if(!empty($pay['is_system']) && $pay['is_system']==1)
    {
        make_json_error('系统参数无法删除');      	
    }
    $pay_count  = $db->getOne('SELECT count(*) FROM ' .$os->table('scm_balance_order'). " WHERE pay_type='$pay_id'");
    if($pay_count==0){   
	    if($db->query("DELETE FROM " . $os->table('scm_payment') . " WHERE pay_id='$pay_id'")){
		    /* 记日志 */
		    admin_log($pay['pay_name'], 'remove', 'scm_payment');	
		    $db->query("UPDATE " . $os->table('scm_balance_order') . " SET pay_type=0 WHERE pay_type='$pay_id'");
	    }
    }else{
    	make_json_error('"'. $pay['pay_name'] .'" 还有关联,您不能删除');    	
    }

    /* 清除缓存 */
    clear_cache_files();

    $url = 'scm.php?act=query_payment&' . str_replace('act=remove_payment', '', $_SERVER['QUERY_STRING']);

    os_header("Location: $url\n");
    exit;		
}

elseif($_REQUEST['act']=='list_supplier'){   
    $smarty->assign('supplier_type_list', supplier_type_list(0));	
    $list = get_supplier_list();  
    
    $smarty->assign('supplier_list', $list['supplier']);    
    $smarty->assign('filter',        $list['filter']);
    $smarty->assign('page_count',    $list['page_count']); 
    $smarty->assign('record_count',  $list['record_count']);
    $smarty->assign('full_page',    1);
       
    assign_query_info();    	
    $smarty->display('supplier_dialog_info.tpl');  	
}

elseif($_REQUEST['act']=='query_supplier'){
    $list = get_supplier_list();
    $smarty->assign('supplier_list',  $list['supplier']);
    $smarty->assign('filter',         $list['filter']);
    $smarty->assign('record_count',   $list['record_count']);
    $smarty->assign('page_count',     $list['page_count']);
    
    make_json_result($smarty->fetch('supplier_dialog_info.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count'])); 	
}

elseif ($_REQUEST['act'] == 'search_goods'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON();
    
	$supplier_id = empty($_REQUEST['supplier_id']) ? 0 : intval($_GET['supplier_id']);
    $keyword = empty($_GET['keyword']) ? '' : json_str_iconv(trim($_GET['keyword']));

    $result = array('error'=>0, 'message'=>'', 'content'=>'');
    
    if($supplier_id > 0){
        $sql = "SELECT g.goods_id,g.goods_name,g.goods_sn FROM " . $os->table('supplier_goods') . 
               " sg JOIN " . $os->table('goods') . " g ON sg.goods_id=g.goods_id WHERE g.is_delete=0" . 
               " AND sg.is_open=1 AND sg.supplier_id='$supplier_id' AND (g.goods_id LIKE '%" . 
               mysql_like_quote($keyword) . "%'" . " OR g.goods_name LIKE '%" . mysql_like_quote($keyword) . 
               "%' OR g.goods_sn LIKE '%" . mysql_like_quote($keyword) . "%')";	   
    }else{
        $sql = "SELECT g.goods_id,g.goods_name,g.goods_sn FROM " . $os->table('goods') . " g WHERE " . 
               "g.is_delete=0 AND (g.goods_id LIKE '%" . mysql_like_quote($keyword) . "%' OR g.goods_name " . 
               " LIKE '%" . mysql_like_quote($keyword) . "%'" . " OR g.goods_sn LIKE '%" . mysql_like_quote($keyword) . 
               "%')";		    	
    }
    $res = $db->query($sql);
    $result['goodslist'] = array();
    while ($row = $db->fetchRow($res))
    {
        $result['goodslist'][] = array('goods_id' => $row['goods_id'], 'name' => $row['goods_id'] . '  ' . $row['goods_name'] . '  ' . $row['goods_sn']);
    }
    die($json->encode($result));
}

elseif($_REQUEST['act']=='get_goods_info'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    
    $goods_id = isset($_REQUEST['goods_id']) ? intval($_REQUEST['goods_id']) : 0;
    $order_id = isset($_REQUEST['order_id']) ? intval($_REQUEST['order_id']) : 0;
    $order_type   = trim($_GET['type']);
    
    if (empty($goods_id))
    {
        make_json_response('', 1, '无法获取系列产品详细信息');
    }
    $order = get_fast_scm_order_info($order_type, $order_id);
    if(empty($order)){
		make_json_error(fast_scm_order_ur($order_type).'不存在');
    }
    
    $json = new JSON();
        
	/* 取得商品信息 */
	$sql = "SELECT g.goods_id, c.cat_name, g.goods_sn, g.goods_name, b.brand_name, " .
	       "g.goods_number, g.market_price, g.shop_price, g.promote_price, " .
	       "g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_type, g.is_promote " .
	       "FROM " . $os->table('goods') . " g LEFT JOIN " . $os->table('brand') . 
	       " b ON g.brand_id = b.brand_id LEFT JOIN " . $os->table('category') . 
	       " c ON g.cat_id = c.cat_id WHERE g.is_delete=0 AND g.goods_id = '$goods_id'";
	$goods = $db->getRow($sql);
	
	if($order_type!='check'){
		$goods['goods_brief']  = $db->getOne("SELECT goods_brief FROM " . $os->table('supplier_goods') . " WHERE " . 
		                                     "is_open=1 AND supplier_id='$order[supplier_id]' AND goods_id='$goods_id'"); 
		$goods['norm_price']   = $goods['shop_price'];
		$goods['discount']     = $order['discount'];
		$goods['actual_price'] = round($goods['norm_price'] * $goods['discount'], 2);                                    
	}else{
		$goods['actual_price'] = price_format(abs($goods['shop_price']), false);
	}                    


	/* 取得商品属性 */
	$sql = "SELECT c.color_id c_id,c.color_name c_name,c.img_file AS img_url,'color' AS c_type FROM " . 
		   $os->table('goods_color') . " gc LEFT JOIN " . $os->table('color') . 
	       " c ON c.color_id=gc.color_id WHERE gc.goods_id=$goods_id UNION " . 
	       "SELECT s.size_id c_id,s.size_name c_name,'' AS img_url,'size' AS c_type FROM " . 
	       $os->table('goods_size') . " gs LEFT JOIN " . $os->table('size') . 
	       " s ON gs.size_id=s.size_id WHERE gs.goods_id=$goods_id";
	$attr_list = $db->getAll($sql);	
	$goods['attr_list'] = $attr_list;	
	echo $json->encode($goods);	
}
?>